﻿using System;
using System.Collections.Generic;
using System.Text;

namespace deFramework.BusinessRules
{
    /// <summary>
    /// 
    /// </summary>
    public class SpWebMenuTools : Base.BaseBusinessRule
    {

        #region "Constructor, private Variables"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aContext"></param>
        public SpWebMenuTools(ref Common.PresentationContext aContext) : base(ref aContext) { }

        private string kPropertyName_DeactivationWebPartsToRemove = "DeactivationWebPartsToRemove";

        #endregion



        #region "Public - AddLinkToQuickLaunchCategory, DeactivationRemoveWebPartsFromGallery, RemoveLinkFromQuickLaunchCategory"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aTitle"></param>
        /// <param name="aCategory"></param>
        /// <param name="aRelativeUrl"></param>
        /// <returns></returns>
        public bool AddLinkToQuickLaunchCategory(string aTitle, string aCategory, string aRelativeUrl)
        {
            bool l_Result = false;
            try
            {
                if (this.MyContext.SpWebInContext)
                {
                    this.Do_AddLinkToQuickLaunchCategory(aTitle, aCategory, aRelativeUrl);
                    l_Result = true;
                }
            }
            catch (Exception ex)
            {
                this.CurrentException = ex; 
            }
            return l_Result;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool DeactivationRemoveWebPartsFromGallery()
        {
            bool l_Result = false;
            try
            {
                if (this.MyContext.FeatureInContext)
                {
                    this.FeatureDo_DeactivationRemoveWebPartsFromGallery();
                    l_Result = true;
                }
                else
                {
                    //this.mLog.StandardLog("SpWebMenuTools.DeactivationRemoveWebPartsFromGallery",
                    //    "information", "this.mContext.FeatureInContext is FALSE");
                }
            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
                //this.mLog.BasicException(ex, "SpWebMenuTools.DeactivationRemoveWebPartsFromGallery");
            }
            return l_Result;
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="aKbTitle"></param>
        /// <param name="aKbCategory"></param>
        /// <returns></returns>
        public bool RemoveLinkFromQuickLaunchCategory(string aKbTitle, string aKbCategory)
        {
            bool l_Result = false;
            try
            {
                if (this.MyContext.SpWebInContext)
                {
                    this.Do_RemoveLinkFromQuickLaunchCategory(aKbTitle, aKbCategory);
                    l_Result = true;
                }
                //else
                //{
                //    //this.mLog.StandardLog("SpWebMenuTools.RemoveLinkFromQuickLaunchCategory",
                //    //    "information", "this.mContext.FeatureInContext is FALSE");
                //}
            }
            catch (Exception ex)
            {
                this.CurrentException = ex; 
                //this.mLog.BasicException(ex, "SpWebMenuTools.RemoveLinkFromQuickLaunchCategory");
            }
            return l_Result;
        }




        #endregion


        #region "Private FeatureDOs - AddLinkToQuickLaunchCategory, DeactivationRemoveWebPartsFromGallery, RemoveLinkFromQuickLaunchCategory"

        private void Do_AddLinkToQuickLaunchCategory(string aKbTitle, string aKbCategory, string aRelativeUrl)
        {
            Microsoft.SharePoint.Navigation.SPNavigationNodeCollection quickLaunchNodes = this.MyContext.MySpWeb.Navigation.QuickLaunch;
            Microsoft.SharePoint.Navigation.SPNavigationNode newNode =
                new Microsoft.SharePoint.Navigation.SPNavigationNode(aKbTitle,
                aRelativeUrl, false);
            this.InsertNavNodeToCollectionAsChild(this.MyContext.MySpWeb, newNode, quickLaunchNodes, aKbCategory);
        }



        private void FeatureDo_DeactivationRemoveWebPartsFromGallery()
        {
            Microsoft.SharePoint.SPFeatureProperty fRemoveFromGallery =
                this.MyContext.FeatureProperties.Feature.Properties[
                this.kPropertyName_DeactivationWebPartsToRemove];
            string[] galleryParts = fRemoveFromGallery.Value.Split(";".ToCharArray());
            this.RemovePartsFromWebPartGallery(galleryParts);
        }

        private void Do_RemoveLinkFromQuickLaunchCategory(string aKbTitle, string aKbCategory)
        {
            Microsoft.SharePoint.Navigation.SPNavigationNodeCollection quickLaunchNodes = this.MyContext.MySpWeb.Navigation.QuickLaunch;
            foreach (Microsoft.SharePoint.Navigation.SPNavigationNode node in quickLaunchNodes)
            {
                if (this.CheckNodeToDelete(node, aKbTitle, aKbCategory))
                    break;
            }
        }


        #endregion






        #region "Private -	InsertNavNodeToCollectionAsChild, CheckNodeToDelete, RemovePartsFromWebPartGallery"


        private void InsertNavNodeToCollectionAsChild(Microsoft.SharePoint.SPWeb rootWeb,
        Microsoft.SharePoint.Navigation.SPNavigationNode nodeToInsert,
        Microsoft.SharePoint.Navigation.SPNavigationNodeCollection targetNodeCollection,
        string parentNodeTitle)
        {
            bool hasParentNode = false;
            foreach (Microsoft.SharePoint.Navigation.SPNavigationNode node in targetNodeCollection)
            {
                if (parentNodeTitle == node.Title)
                {
                    //Found the required parent node, add to it,
                    //set up our test variable, update and break from the loop
                    hasParentNode = true;
                    node.Children.AddAsFirst(nodeToInsert);
                    node.Update();
                    //nodeToInsert.Url = this.mContext.MySpWeb.Site.Url; 
                    node.Update();
                    break;
                }
            }

            if (!hasParentNode)
            {
                //the desired parent node doesn't exist so create it ;o)
                //create as external so that no attempt to maintain is made by WSS
                Microsoft.SharePoint.Navigation.SPNavigationNode newTreeNode = new Microsoft.SharePoint.Navigation.SPNavigationNode(parentNodeTitle, "", true);

                //add the parent at the end of the targetNodeCollection
                targetNodeCollection.AddAsLast(newTreeNode);
                newTreeNode.Update();

                try
                {
                    //Add our new site collection node to it's parent
                    newTreeNode.Children.AddAsFirst(nodeToInsert);
                    nodeToInsert.Update();
                }
                catch (Exception ex)
                {
                    Microsoft.SharePoint.Navigation.SPNavigationNode ErrTreeNode =
                        new Microsoft.SharePoint.Navigation.SPNavigationNode(ex.Message, "", true);
                    targetNodeCollection.AddAsLast(ErrTreeNode);
                    ErrTreeNode.Update();
                }
            }

            //call update to make everything 'stick'
            rootWeb.Update();
        }




        private bool CheckNodeToDelete(Microsoft.SharePoint.Navigation.SPNavigationNode node, string aTitle, string aCategory)
        {
            bool l_Result = false;
            if (aCategory == node.Title)
            {
                foreach (Microsoft.SharePoint.Navigation.SPNavigationNode childNode in node.Children)
                {
                    if (aTitle == childNode.Title)
                    {
                        //Found the required parent node, add to it,
                        //set up our test variable, update and break from the loop
                        childNode.Delete();
                        this.MyContext.MySpWeb.Update();
                        l_Result = true;
                        break;
                    }
                }
                //Found the required parent node, add to it,
                //set up our test variable, update and break from the loop
                //node.Delete();
                this.MyContext.MySpWeb.Update();
                l_Result = true;
            }
            return l_Result;
        }


        /// <summary>
        /// Remove web parts from the site collection web part gallery
        /// </summary>
        /// <param name="removeFromGallery">web parts to remove</param>
        private void RemovePartsFromWebPartGallery(string[] removeFromGallery)
        {
            using (Microsoft.SharePoint.SPWeb rootWeb = this.MyContext.MySpWeb)
            {
                //remove web parts from the web part gallery
                using (Microsoft.SharePoint.SPSite site = rootWeb.Site)
                {
                    Microsoft.SharePoint.SPList webPartCatalog = site.GetCatalog(Microsoft.SharePoint.SPListTemplateType.WebPartCatalog);
                    if (webPartCatalog != null)
                    {
                        System.Collections.Generic.List<Guid> matchingWebParts =
                            new System.Collections.Generic.List<Guid>();
                        foreach (Microsoft.SharePoint.SPListItem item in webPartCatalog.Items)
                        {
                            Predicate<string> exists = delegate(string p) { return p.Trim().ToLower().Equals(item.Name.ToLower()); };
                            if (Array.Exists<string>(removeFromGallery, exists))
                            {
                                //WriteLog(TraceProvider.TraceSeverity.Verbose, traceCategoryName, 
                                //"***!!!Web Part in list...marked for removal" );
                                matchingWebParts.Add(item.UniqueId);
                            }
                        }
                        //now loop and remove
                        for (int i = 0; i < matchingWebParts.Count; i++)
                        {
                            //WriteLog(TraceProvider.TraceSeverity.InformationEvent, traceCategoryName, 
                            //string.Format( "Removing: {0} {1}", webPartCatalog.Items[matchingWebParts[i]].Name, matchingWebParts[i].ToString() ) );
                            webPartCatalog.Items[matchingWebParts[i]].Delete();
                            // WriteLog(TraceProvider.TraceSeverity.Verbose, traceCategoryName, "Removed" );
                        }
                    }
                    else
                    {
                        // WriteLog(TraceProvider.TraceSeverity.Exception, traceCategoryName, 
                        // "Web Part Gallery returned a null reference" );
                    }
                }
            }
        }


        #endregion


    }
}
